package com.openflag.bwicservice.controller;

import com.openflag.bwicservice.domain.*;

import com.openflag.bwicservice.repository.BwicRepository;
import com.openflag.bwicservice.repository.ServiceChargeRepository;

import com.openflag.bwicservice.service.SaleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Optional;

import static com.openflag.bwicservice.domain.ResultStatus.*;
import static com.openflag.bwicservice.util.ResultUtil.*;
@RestController
@RequestMapping("/sale")
@CrossOrigin("*")
public class SaleController {

    @Autowired
    private ServiceChargeRepository serviceChargeRepository;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SaleService saleService;

    @Autowired
    private BwicRepository bwicRepository;


    @PostMapping("/servicechargechange")
    public Result<ServiceCharge> setServiceCharge(@RequestBody ServiceChargeRequest serviceChargeRequest) {

        ServiceCharge serviceCharge = new ServiceCharge();


        if (serviceChargeRequest.getCharge()<0.0 || serviceChargeRequest.getCharge()>1.0){
            return fail(SERVICE_CHARGE_WRONG);
        }
        Integer position = restTemplate.getForObject("http://localhost:8087/position/{id}",
                Integer.class,serviceChargeRequest.getClientId());
        if (position != 0){
            return fail(SERVICE_CHARGE_POSITION_WRONG);
        }

        serviceCharge.setCharge(serviceChargeRequest.getCharge());
        serviceCharge.setId(1L);

        serviceChargeRepository.save(serviceCharge);

        return success(serviceCharge);


    }

    @GetMapping("/servicechargeget")
    public Result<Double> getServiceCharge(){
        Double rate = serviceChargeRepository.getServiceCharge();

        return success(rate);
    }

    @GetMapping("/uncheckedList")
    public Result<List<Bwic>> getUncheckedBwic(){
        return saleService.uncheckBwicList();

    }

    @PostMapping("/checkbwic")
    public Result<List<Bwic>> checkUncheckedBwic(@RequestBody CheckBwicRequest checkBwicRequest){
        Bwic queryBwic = new Bwic();

        queryBwic.setId(checkBwicRequest.getBwicId());

        Optional<Bwic> optionalBwic = bwicRepository.findOne(Example.of(queryBwic));

        if (optionalBwic.isPresent()){
            Boolean yesorno = checkBwicRequest.getPassOrNot();
            if (yesorno == true){

                optionalBwic.get().setStatus(4);

            }else{
                optionalBwic.get().setStatus(2);

            }
            bwicRepository.save(optionalBwic.get());

            return saleService.uncheckBwicList();
        }else {
            return fail(BWIC_NOT_EXIST);
        }



    }



}
